package com.sdgakj.web.person;

import com.alibaba.fastjson.JSONObject;
import com.sdgakj.common.other.StringUtil;
import com.sdgakj.entity.*;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 鲁俊杰 on 2017/4/28.
 */
@Controller
@RequestMapping(value = "/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    private static Logger logger = LoggerFactory.getLogger(PersonController.class);

    private static final String PAGE_SIZE = "10";

    /**
     * 列表
     * @param pageNumber 页号
     * @param pageSize   每页大小
     * @param sortType   排序字段
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value="/list",method = RequestMethod.GET)
    public String list(@RequestParam(value = "fId", defaultValue = "0") Long fId,
                       @RequestParam(value = "page", defaultValue = "1") int pageNumber,
                       @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
                       @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
                       ServletRequest request) {
        Map<String,Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        if (fId!=0L){
            searchParams.put("EQ_fId", fId);
        }
        Page<Person> persons = null;
        try{
            persons = personService.getPersonByPage(searchParams, pageNumber, pageSize, "", sortType);
        }catch (Exception e){
            e.printStackTrace();
        }
        model.addAttribute("persons",persons);
        model.addAttribute("sortType", sortType);
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "person/personList";
    }

    /**
     * 添加家族信息
     * @param entity
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createFamily(@RequestParam(value = "borntimeStr" , defaultValue = "") String borntimeStr,
                               Person entity, RedirectAttributes redirectAttributes) {
        logger.info("save the person");

        if (!StringUtils.isEmpty(borntimeStr)) {
            Date borntime = DateUtil.formatStringToDate(borntimeStr + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            entity.setBornTime(borntime.toString());
        }
        entity.setCreatetime(new Date());
        entity.setUpdatetime(new Date());
        personService.savePerson(entity);
        redirectAttributes.addAttribute("message", "添加成功！");
        return "redirect:/person/list";
    }

    /**
     *
     * @param
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String createDevote(@RequestParam(value = "borntimeStr" , defaultValue = "") String borntimeStr,
                               Person entity, RedirectAttributes redirectAttributes) {

        if (!StringUtils.isEmpty(borntimeStr)) {
            Date borntime = DateUtil.formatStringToDate(borntimeStr + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            entity.setBornTime(borntime.toString());
        }
        entity.setUpdatetime(new Date());
        personService.savePerson(entity);
        redirectAttributes.addFlashAttribute("message", "更新成功");
        return "redirect:/person/list";
    }

    /**
     * 创建订单页面跳转
     *
     * @param
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createDevote( Model model) {
        model.addAttribute("action",  "create");
        return "person/personForm";
    }

    /**
     * 更新订单页面跳转
     *
     * @param
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String updateDevote(@RequestParam(value = "id", defaultValue = "0") Long id, Model model) {
        Person person = personService.getPersonById(id);
        model.addAttribute("person", person);
        model.addAttribute("action",  "update");
        return "person/personForm";
    }

    /**
     * 根据PersonId获取Person
     * @param personId
     * @return
     */
    @RequestMapping(value = "/getPersonDatailById",method = RequestMethod.GET)
    public JSONObject getPersonDatailById(
            @RequestParam(value = "personId" , defaultValue = "") Long personId){
        logger.info("get person detail ...");
        JSONObject result = new JSONObject();
        try{
            result.put("data",personService.getPersonById(personId));
            result.put("resMsg","成功");
            result.put("resCode","1");
        }catch (Exception e){
            result.put("resMsg","失败");
            result.put("resCode","0");
        }
        return result;
    }

    /**
     * 通过familyId获取person集合
     * @param familyId
     * @return
     */
    @RequestMapping(value = "/getPersonsByFamilyId",method = RequestMethod.GET)
    public JSONObject getPersonsByFamilyId(@RequestParam(value = "familyId") Long familyId,
                                            @RequestParam(value = "page" ,defaultValue = "1") Integer page,
                                            @RequestParam(value = "pageSize",defaultValue = PAGE_SIZE) Integer pageSize){
        JSONObject result=new JSONObject();
        List<Person> personList;
        try {
            //personList=personService.getPersonsByFid(familyId);
            personList=personService.getPersonsByFId(familyId,page,pageSize);
            result.put("data",personList);
            result.put("resMsg","获取数据成功");
            result.put("resCode","1");
        }catch (Exception e){
            result.put("resMsg","获取数据失败");
            result.put("resCode","0");
        }
        return result;
    }

    /**
     * 根据personId删除用户
     * @param personId
     * @param userId 操作的用户
     * @return
     */
    @RequestMapping(value = "/deletePersonById",method = RequestMethod.GET)
    public JSONObject deletePersonById(@RequestParam(value = "personId" ,required = true) Long personId,
                                        @RequestParam(value = "userId" ,required = true) Long userId){
        JSONObject result=new JSONObject();
        try {
            personService.deletePersonById(personId);
            result.put("resMsg","删除成功！");
            result.put("resCode","1");
        }catch (Exception e){
            result.put("resMsg","删除失败！");
            result.put("resCode","0");
        }
        return  result;
    }

    /**
     * 添加新的person
     * @param jsonData
     * @return
     */
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public JSONObject addPerson(String jsonData){ //@RequestParam(value = "data")

        JSONObject result=new JSONObject();
        if (StringUtil.isBlank(jsonData) || "null".equals(jsonData)) {
            result.put("resCode", "0");
            result.put("resMsg", "请求参数错误!");
            return result;
        }

        ObjectMapper mapper=new ObjectMapper();
        Map map;

        try {
            map = mapper.readValue(jsonData, Map.class);
        } catch (Exception e) {
            result.put("resCode", "0");
            result.put("resMsg", "数据解析错误!检查JSON格式!");
            return result;
        }
        /**
         * 添加person的同时更新relations（关系）表
         */
        Long id=Long.getLong(map.get("id").toString());//需要添加父母或者孩子的persnId
        String name=String.valueOf(map.get("name"));
        String age=String.valueOf(map.get("age"));
        String gender=String.valueOf(map.get("gender"));
        Integer alive=Integer.parseInt(String.valueOf(map.get("alive")));
        String description=String.valueOf(map.get("description"));
        SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        Date bornTime;
        try {
            bornTime=sdf.parse(String.valueOf(map.get("bornTime")));
        }catch (Exception e){
            result.put("resCode", "0");
            result.put("resMsg", "日期解析错误!检查JSON格式!");
            return result;
        }
        String bornAddress=String.valueOf(map.get("bornAddress"));
        String avatar=String.valueOf(map.get("avatar"));
        Integer generation=Integer.parseInt(String.valueOf(map.get("generation")));
        String position=String.valueOf(map.get("position"));

        String flag=String.valueOf(map.get("flag"));
        String rel = String.valueOf(map.get("rel"));
        Long familyId=Long.getLong(String.valueOf(map.get("f_id")));
        Long source=Long.getLong(String.valueOf(map.get("source")));
        Long target=Long.getLong(String.valueOf(map.get("target")));
        /**
         * 还有其他的属性
         */


        /**
         * 步骤如下：
         * 1.获取person所有的属性值
         * 2.将封装进person实体中
         * 3.保存person信息，返回personId
         * 4.再根据返回的关系（child、marride、target、source），更新relations表的信息
         */
        /**
         * 通过set方法给person赋值
         */
        Person person=new Person();
        person.setName(name);
        person.setCreatetime(new Date());
        person.setAge(age);
        person.setAlive(alive);
        person.setBornAddress(bornAddress);
        person.setS(gender);

        person=personService.getPersonById(id);

        Long personId = personService.savePerson(person);
        /**
         * 更新relations表的信息
            1.先根据rel判断是父子（母子）（rel==“child”）关系还是夫妻（rel==“married”）关系
            2.如果确定是父子关系，再根据flag判断添加的是父亲还是孩子
            3.如果添加的是孩子（flag==0），target等于新添加的personId，source等于传过来的id
            4.如果添加的是孩子（flag==1），target等于传过来的id，source等于新添加的personId
            5.如果是夫妻关系，根据flag判断添加的是（flag==0）妻子还是（flag==1）丈夫
            6.如果添加的妻子，target等于新添加的personId，source等于传过来的id
            7.如果添加的丈夫，target等于传过来的id，source等于新添加的personId
         */
        return result;
    }

}
